﻿namespace SCRS.View;

public static class WindowManager
{
    // 1. 管理窗口何时被创建
    // 2. 管理窗口何时被显示
    // 3. 管理窗口何时被关闭
    // 4. 管理窗口何时被销毁
    private static Dictionary<string,Func<Form>> _dicFormFactory = new();
   
    private static Dictionary<string,Form> _dicFormInstance = new();

    /// <summary>
    /// 注册窗口工厂
    /// </summary>
    /// <param name="key"></param>
    /// <param name="formFactory"></param>
    public static void Register(string key, Func<Form> formFactory)
    {
        _dicFormFactory[key] = formFactory;
    }

    /// <summary>
    /// 获得窗口实例
    /// </summary>
    /// <param name="key"></param>
    /// <returns></returns>
    /// <exception cref="Exception"></exception>
    public static Form Get(string key)
    {
        // 1. 如果窗口还未创建,则创建窗口
        if (!_dicFormInstance.TryGetValue(key,out var form))
        {
            // 2. 查找窗口的创建工厂
            if (!_dicFormFactory.TryGetValue(key, out var formFactory))
            {
                throw new Exception($"未找到窗口{key}的创建工厂");
            }
            form = formFactory();
            // 3. 缓存窗口实例
            _dicFormInstance[key] = form;
            // 4. 窗口关闭时,从缓存中移除
            form.FormClosed += (sender, args) =>
            {
                _dicFormInstance.Remove(key);
            };
        }
        return form;
    }

    /// <summary>
    /// 设置窗口是否可见
    /// </summary>
    /// <param name="formKey">窗口代码</param>
    /// <param name="visible">显示状态</param>
    /// <param name="dialog">是否是模态窗体</param>
    /// <param name="owner">父窗口</param>
    /// <returns></returns>
    public static Form SetVisible(string formKey, bool visible,bool dialog = false,Form? owner = null)
    {
        var form = Get(formKey);
        form.Owner = owner;
        if (visible)
        {
            if (dialog)
            {
                form.ShowDialog();
            }
            else
            {
                form.Show();
            }
        }
        else
        {
            form.Hide();
        }
        return form;
    }

    /// <summary>
    /// 显示窗口
    /// </summary>
    /// <param name="formKey"></param>
    /// <param name="dialog"></param>
    /// <param name="owner"></param>
    /// <returns></returns>
    public static Form Show(string formKey, bool dialog, Form? owner = null)
    {
        return SetVisible(formKey, true, dialog, owner);
    }
    /// <summary>
    /// 隐藏窗口
    /// </summary>
    /// <param name="formKey"></param>
    public static void Hide(string formKey)
    {
        SetVisible(formKey, false);
    }

    /// <summary>
    /// 关闭窗口
    /// </summary>
    /// <param name="formKey"></param>
    public static void Close(string formKey)
    {
        var form = Get(formKey);
        form.Close();
    }


    // 隐藏当前窗口,显示新窗口

    public static Form Show( this Form currentForm,string formKey, bool dialog = false,Form? owner = null)
    {
        currentForm.Hide();
        return Show(formKey, dialog, owner);
    }
}